var trClone; // first loaded tr is cloned
$(function() {
    var tableScope = $('#list_activities');
    var tableScopeBody = $('tbody:first', tableScope);
    
    // add row
    $('#add_row').live("click", function(e) {
        var lastRow = $('tr.row_list_activities:last', tableScope);
        
        // make sure exists one row on tableScope
        if ( lastRow.length ) {
            // preformating the clone
            newRow = preformatNewRow(lastRow.clone());
            
            // cache for later use
            if ( typeof(trClone) == 'undefined' ) {
                trClone = newRow;
            }
            // tableScopeBody.append(newRow);
            $('.add_description_row:last', tableScope).after(newRow);
            
            // show hidden
            $('.row_list_activities:last .specialCol', tableScope).each(function() {
                $(this).children().show();
            });
            
            $('.student_class_id:last', tableScope).change(function(e) {
                bindGetStudents(e);
                bindGetCourses(e);
            });
            
            $('.activity_id:last', tableScope).change(function(e) {
                bindCheckSpecialCol(e);
            }).trigger('change');
        }
    });
    
    // delete row
    $('#del_row').click(function(e) {
        var totalCb = $('.cb_list_activities').length;
        var totalChecked = $('.cb_list_activities:checked').length;
        
        if ( totalChecked == 0 ) {
            alert('Centang kegiatan yang ingin Anda hapus pada kotak\n'+
                  'kecil sebelah kiri pilihan kegiatan'
            );
            return false;
        }
        
        if ( totalChecked < totalCb ) {
            $('.cb_list_activities:checked').each(function(idx) {
                var rowId = $(this).parent().parent().attr('id');
                $('tr[id^=' + rowId + ']').remove();
                $('#rg' + rowId.substr(1)).remove();
            });
        } else {
            alert('Anda tidak dapat menghapus kegiatan ini,\n' +
                  'karena harus ada 1 kegiatan yang tersisa, jika ada\n' +
                  'lebih dari 1 kegiatan, maka kegiatan ini dapat dihapus'
            );
            return false;
        }
        
        e.preventDefault();
    });
    
    // add description
    $('.add_description').live('click', function(){
        var row = $('#r'+this.id.substr(1));
        var newRow = preformatNewDesc(row.clone());
        $('#rg'+this.id.substr(1)).before(newRow);
            
        $('.student_class_id:first', newRow).change(function(e) {
            bindGetStudents(e);
            bindGetCourses(e);
        });
    });
    
    // delete description
    $('.del_description').live('click', function(){
        var rel = $(this).attr('rel');
        var trRemoved = $('#'+rel);
        if ( trRemoved.hasClass('row_list_activity_descriptions') ) {
            trRemoved.remove();
        } else {
            alert('Anda tidak dapat menghapus sub kegiatan pertama.\n' +
                  'Tapi Dengan menghapus kegiatannya,\n' +
                  'Anda juga akan menghapus semua sub kegiatannya'
            );
            return false;
        }
    });
    
    $('.student_class_id').change(function(e) {
        bindGetStudents(e);
        bindGetCourses(e);
    });
    
    // colorize special activities
    $('.activity_id option').each(function() {
        if ( $(this).val() in special_activities ) {
            $(this).css({'color': 'red', 'font-weight': 'bold'});
        }
    });
    
    $('.activity_id').change(function(e) {
        bindCheckSpecialCol(e);
    }).trigger('change');
});

/**
 * Function to format new tr after
 * #add_row is clicked
 * @param dom tr cloned row to be formatted before appended into tbody
 * @return dom tr after formatted
 */
function preformatNewRow(tr) {
    // get row-xth
    // and increment it
    var oldId = tr.attr('id').substr(1)*1;
    var newId = oldId+1;
    $(tr).attr('id', 'r' + newId);
    
    // rel is
    $(tr).attr('rel', 'r' + newId + '_d0');
    
    // change index of all input elements (list_Activities)
    $('.cb_list_Activities:first', tr).attr('name', 'data[ActList][ActListActivity][' + 
        newId + '][id]');
    $('.activity_id:first', tr).attr('name', 'data[ActList][ActListActivity][' + 
        newId + '][activity_id]').val('');
    $('.del_description:first', tr).attr('rel', 'r' + newId + '_d0');
    
    // change index of all input elements (list_activity_descriptions)
    $('.student_class_id:first', tr).attr('name', 'data[ActList][ActListActivity]['+newId+']' +
        '[ActListActivityDescription][0][student_class_id]').val('');
    $('.course_id:first', tr).attr('name', 'data[ActList][ActListActivity]['+newId+']' +
        '[ActListActivityDescription][0][course_id]').val('');
    
    $('.start_class:first', tr).attr('name', 'data[ActList][ActListActivity]['+newId+']' +
        '[ActListActivityDescription][0][start_class]');
    $('.end_class:first', tr).attr('name', 'data[ActList][ActListActivity]['+newId+']' +
        '[ActListActivityDescription][0][end_class]');
        
    $('.student_lists:first', tr).html('');
        
    $('.description:first', tr).attr('name', 'data[ActList][ActListActivity]['+newId+']' +
        '[ActListActivityDescription][0][description]');
    $('.assignment_no:first', tr).attr('name', 'data[ActList][ActListActivity]['+newId+']' +
        '[ActListActivityDescription][0][assignment_no]');
    $('.result:first', tr).attr('name', 'data[ActList][ActListActivity]['+newId+']' +
        '[ActListActivityDescription][0][result]');
    
    // added add_description_row
    var dr = $('#rg' + oldId).clone();
    dr.attr('id', 'rg' + newId );
    $('#b'+oldId, dr).attr('id', 'b'+newId);
    
    var ret = $('<div id="ret'+newId+'"></div>').html(tr).append(dr);
    
    return ret.html();
}

/**
 * Function to format new tr after
 * .add_description is clicked
 * @param dom tr cloned row to be formatted before inserted before #rgx
 * @return dom tr after formatted
 */
function preformatNewDesc(tr) {
    // get add_description_row
    var rowId = tr.attr('id').substr(1)*1;
    
    // get description-xth
    // and increment it
    // var oldId = tr.attr('rel').substr(1)*1;
    var o = $('tr[id^=r' + rowId + ']:last').attr('rel').split('_');
    var oldId = o[1].substring(1)*1;
    var newId = oldId+1;
    
    $(tr).removeClass('row_list_activities');
    $(tr).addClass('row_list_activity_descriptions');
    tr.attr('id', 'r'+rowId+'_d'+newId);
    tr.attr('rel', 'r'+rowId+'_d'+newId);
    
    // change index of all input elements (list_Activities)
    $('.cb_list_Activities:first', tr).parent().addClass('empty').children().remove();
    $('.activity_id:first', tr).parent().addClass('empty').children().remove();
    $('.del_description:first', tr).attr('rel', 'r'+rowId+'_d'+newId);
    
    // change index of all input elements (list_activity_description)
    $('.student_class_id:first', tr).attr('name', 'data[ActList][ActListActivity]['+rowId+']' +
        '[ActListActivityDescription]['+newId+'][student_class_id]').val('');
    $('.course_id:first', tr).attr('name', 'data[ActList][ActListActivity]['+rowId+']' +
        '[ActListActivityDescription]['+newId+'][course_id]').val('');
    
    $('.start_class:first', tr).attr('name', 'data[ActList][ActListActivity]['+rowId+']' +
        '[ActListActivityDescription]['+newId+'][start_class]');
    $('.end_class:first', tr).attr('name', 'data[ActList][ActListActivity]['+rowId+']' +
        '[ActListActivityDescription]['+newId+'][end_class]');
    
    $('.student_lists:first', tr).html('');
    
    $('.description:first', tr).attr('name', 'data[ActList][ActListActivity]['+rowId+']' +
        '[ActListActivityDescription]['+newId+'][description]');
    $('.assignment_no:first', tr).attr('name', 'data[ActList][ActListActivity]['+rowId+']' +
        '[ActListActivityDescription]['+newId+'][assignment_no]');
    $('.result:first', tr).attr('name', 'data[ActList][ActListActivity]['+rowId+']' +
        '[ActListActivityDescription]['+newId+'][result]');
    
    return tr;
}

function bindGetStudents(e) {
    var el  = $(e.target);
    var row = el.parent().parent();
    
    if ( el.val() ) {
        $.get(getStudents + el.val(), function(resp) {
            var name = $('.student_class_id:first', row).attr('name');
            name = name.replace(/\[student_class_id\]/g,'[student_id][]');
            
            $('.student_lists', row).html(resp);
            $('.student_id', row).each(function(idx) {
                $(this).attr('name', name);
            });
        });
    } else {
        var select = '<select multiple="multiple"><option value=""></option></select>';
        $('.student_lists', row).html(select);
    }
}

function bindGetCourses(e) {
    var el  = $(e.target);
    var row = el.parent().parent();
    
    if ( el.val() ) {
        $.get(getCourses + el.val(), function(resp) {
            $('.course_id', row).html(resp);
        });
    } else {
        var options = '<option value=""></option>';
        $('.course_id', row).html(options);
    }
}

function bindCheckSpecialCol(e) {
    var el  = $(e.target);
    var row = el.parent().parent();
    
    if ( el.val() in special_activities ) {
        $('.specialCol', row).children().show();
    } else {
        $('.specialCol', row).children().hide();
    }
}
